package com.authine.cloudpivot.ext.applicationservice.report;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.ReportTemplateDto;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName ReportTemplateService
 * @Description: 定制报表服务
 * @Author fj
 * @Date 2021/11/4
 * @Version V1.0
 **/
@Path("ReportTemplateService")
@Slf4j
public class ReportTemplateService {
    /**
     * 获取定制报表模板列表
     *
     * @param reportTemplateDto 模板信息
     * @return 模板列表
     */
    @Path("getReportTemplateList")
    @POST
    @Operation(summary = "获取定制报表模板列表", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> getReportTemplateList(@Parameter ReportTemplateDto reportTemplateDto) {
        if (StringUtils.isEmpty(reportTemplateDto.getType())) {
            return SingleResponse.error("-1", "模板类型不能为空");
        }
        if (StringUtils.isEmpty(reportTemplateDto.getOrganizationId())) {
            return SingleResponse.error("-1", "询价组织id不能为空");
        }
        // 根据code查询报表
        List<Map<String, Object>> reportTemplateList = Objects.requireNonNull(JdbcTemplateUtils.builder(ModelConst.T_REPORT_TEMPLATE)
                .selectField("*"), ErrorCodeEnum.BIZ_EXCEPTION.getErrCode())
                .eq("organization_id -> '$.id'", reportTemplateDto.getOrganizationId())
                .eq("type", reportTemplateDto.getType())
                .queryForList();
        BOList boList = new BOList();
        if (CollectionUtils.isEmpty(reportTemplateList)) {
            boList.setData(Lists.newArrayList());
        } else {
            BoResultFormat.resultFormat(reportTemplateList, ModelConst.T_REPORT_TEMPLATE);
            boList.setData(reportTemplateList);

        }
        boList.setSchemaCode(ModelConst.T_REPORT_TEMPLATE);
        boList.setTotal(boList.getData().size());
        return SingleResponse.of(boList);
    }
}
